package com.yb.xczx.cloud.media.controller.test;

import com.yb.core.model.XczxResult;
import io.minio.BucketExistsArgs;
import io.minio.MakeBucketArgs;
import io.minio.MinioClient;
import io.minio.UploadObjectArgs;
import io.minio.errors.MinioException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;

/**
 * Copyright (C), 2022-2023, 姚兵
 * Author: 32210
 * Date: 2023/5/9 21:45
 * FileName: MinioController
 * Description:
 */

@RestController
@RequestMapping("minio")
public class MinioController {
    @Autowired
    MinioClient minioClient;

    @RequestMapping("upload")
    public XczxResult upload() throws IOException, NoSuchAlgorithmException, InvalidKeyException{
        try {
            // Create a minioClient with the MinIO server playground, its access key and secret key
            // Make 'asiatrip' bucket if not exist.
            boolean found =
                    minioClient.bucketExists(BucketExistsArgs.builder().bucket("demo.bucket").build());
            if (!found) {
                // Make a new bucket called 'asiatrip'.
                minioClient.makeBucket(MakeBucketArgs.builder().bucket("demo.bucket").build());
            } else {
                System.out.println("Bucket 'asiatrip' already exists.");
            }

            // Upload '/home/user/Photos/asiaphotos.zip' as object name 'asiaphotos-2015.zip' to bucket
            // 'asiatrip'.
            minioClient.uploadObject(
                    UploadObjectArgs.builder()
                            .bucket("demo.bucket")
                            .object("nba.xlsx")
                            .filename("C:\\Users\\32210\\Desktop\\nba.xlsx")
                            .build());
            System.out.println(
                    "'C:\\Users\\32210\\Desktop\\nba.xlsx' is successfully uploaded as "
                            + "object 'nba.xlsx' to bucket 'demo.bucket'.");
        } catch (MinioException e) {
            System.out.println("Error occurred: " + e);
            System.out.println("HTTP trace: " + e.httpTrace());
        }
        return XczxResult.success();
    }

    public static void main(String[] args) throws Exception {
//        readChunk();
        System.out.println(Runtime.getRuntime().availableProcessors());
    }

    public static void testChunk() throws IOException {
        File sourceFile = new File("D:\\test-chunk\\abc.mp4");
        int chunkSize=1024*1024;
        int chunkNum= (int) Math.ceil(sourceFile.length()*1.0/chunkSize);
        RandomAccessFile rrandom = new RandomAccessFile(sourceFile, "r");
        byte[] bytes=new byte[1024];
        for (int i = 0; i < chunkNum; i++) {
            File chunk = new File("D:\\test-chunk\\chunks\\chunk_" + i);
            RandomAccessFile rwRandom = new RandomAccessFile(chunk, "rw");
            int len=-1;
            while((len=rrandom.read(bytes))!=-1){
                rwRandom.write(bytes,0,len);
                if(chunk.length()>=chunkSize){
                    break;
                }
            }

            rwRandom.close();
        }
        rrandom.close();
    }

    public static void readChunk() throws Exception {
        File target = new File("D:\\test-chunk\\abc_result.mp4");
        File dir = new File("D:\\test-chunk\\chunks");
        File[] files = dir.listFiles();
        List<File> fileList = Arrays.asList(files);
        Collections.sort(fileList,(item1,item2)->{
                   return Integer.valueOf(item1.getName().split("_")[1])
                            -
                            Integer.valueOf(item2.getName().split("_")[1]);
                }
            );

        System.out.println(fileList);
        RandomAccessFile resultFile = new RandomAccessFile(target, "rw");
        fileList.stream().forEach(item->{
            RandomAccessFile rrandom = null;
            try {
                rrandom = new RandomAccessFile(item, "r");
                int len=-1;
                byte[] bytes=new byte[1024];
                while((len=rrandom.read(bytes))!=-1){
                    resultFile.write(bytes,0,len);
                }

            } catch (FileNotFoundException e) {
                throw new RuntimeException(e);
            } catch (IOException e) {
                throw new RuntimeException(e);
            }finally {
                try {
                    rrandom.close();
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }
        });
        fileList.stream().forEach(item->item.delete());
        resultFile.close();
    }
}
